'''
重写认证后端，实现手机号登录
'''
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import User


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            # print('users.util, ModelBackend')
            user = User.objects.get(
                Q(username=username) | Q(mobile=username) | Q(email=username)
            )
        except User.DoesNotExist as e:
            return None
        if user.check_password(password):
            return user
